import React from 'react'
import {useState,useRef} from 'react'
import './index.scss'
import {message,Radio,Button,Input,Modal,Select,Table} from 'antd'
import store from '../../../store/LeiZheng'
import { observer } from 'mobx-react-lite'
// import {ToTopOutlined} from '@ant-design/icons'
const { Option } = Select;
const {goods} = store



function Operate() {
  const [data,setData] = useState([
    {
      id:1,
      imgSrc:'',
      type:'广告链接',
      isRun:false,
      inputVal:''
    },
    {
      id:2,
      imgSrc:'',
      type:'积分商品',
      isRun:true,
      inputVal:''
    }
  ])
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [modalText, setModalText] = useState('我是内容');
  const [selectGoods,setSleGoods] = useState([])
  const searchInput = useRef()

  // const file = useRef()
  const isChecked = (id)=>{
    return (e) =>{
      const newDate = [...data]
      const res = newDate.find(i => i.id === id)
      // console.log(e.target.checked,res);
      res.isRun = e.target.checked
      setData(newDate)
    }
  }
  const uploadFile = (id,e)=>{
    const newDate = [...data]
    const res = newDate.find(i => i.id === id)
    const fileData = e.target.files[0];
    const pettern = /^image/;
    if (!pettern.test(fileData.type)) {
      message.error("图片格式不正确");
      return;
  }
    const reader = new FileReader()
    reader.readAsDataURL(fileData)
    reader.onload = ()=>{
      res.imgSrc = reader.result
      setData(newDate)
    }
  }
  const onChange = (id) => {
    
    return (e)=>{
      const newDate = [...data]
       const res = newDate.find(i => i.id === id)
       res.type = e.target.value
       
       setData(newDate)
    }
  };
  const save = ()=>{
    console.log(data);
    message.success('保存成功！')
  }
  const checkGoods = (id)=>{
    // message.warning('选择中，请稍后……')
    goods.getGoodsData()
    setModalText(id)
    setOpen(true);
  }
  const handlerInput = (id,e)=>{
    // console.log(e.target.value);
    const newDate = [...data]
    const res = newDate.find(i => i.id === id)
    res.inputVal = e.target.value
    setData(newDate)
  }
  const handleOk = () => {
    const res = data.find(v => v.id === modalText)
    // console.log(res);
    res.inputVal = selectGoods.map(v => v.goodsName).join('-')
    setModalText('正在关闭')
    setConfirmLoading(true);
    setTimeout(() => {
      setOpen(false);
      setConfirmLoading(false);
      console.log(selectGoods);
    }, 2000);
  };
  const handleCancel = () => {
    message.info('您取消了')
    setOpen(false);
  };
  const handleChange = (value) => {
    // console.log(`selected ${value}`);
    goods.selectType(value)
  };
  const search = ()=>{
    // console.log(searchInput.current.input.value);
    const length = goods.searchGoods(searchInput.current.input.value)
    if(length === 0) message.warning('未找到')
  }
  const keyUpHandler = (e)=>{
    if(e.key === 'Enter') search()
  }
  //表格
  const columns = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      key: 'goodsName',
      // render: (text) => <a>{text}</a>,
      align:'center',
      className:'col'
    },
    {
      title: '类目',
      dataIndex: 'goodsType',
      key: 'goodsType',
      align:'center',
      className:'col'
    },
  ]
  // console.log(goods.integralGoods);
  
  return (
    <div className='operate'>
      <div className="top">
        {
          data.map((item)=>{
            return (
              <div className='top-item' key={item.id}>
                <div className="hreder">
                  <input type="checkbox" checked={item.isRun} onChange={isChecked(item.id)} /> <span>启动</span>
                </div>
                <section className='box'>
                  <div className="content">
                    <div className="img">
                      <img src={item.imgSrc} alt="这是默认图片"/>
                    </div>
                    <div className="foot">
                      <div className="file">
                      选择图片
                        <input disabled={!item.isRun} type="file" onChange={(e)=>uploadFile(item.id,e)} />
                      {/* <Button type="primary" icon={<ToTopOutlined />}>选择图片</Button> */}
                      </div>
                      <Radio.Group onChange={onChange(item.id)} value={item.type}>
                        <Radio disabled={!item.isRun} value={'广告链接'}>广告链接</Radio>
                        <Radio disabled={!item.isRun} value={'积分商品'}>积分商品</Radio>
                      </Radio.Group>
                      <div className="inp">
                        <Input placeholder={item.type} style={{height:'30px'}}
                         disabled={!item.isRun} value={item.inputVal} onChange={(e)=>handlerInput(item.id,e)} />
                        <Button type="primary"
                         size='small'
                         style={{marginLeft:'5px',display:item.type==='广告链接'?'none':'block'}}
                          onClick={()=>checkGoods(item.id)} disabled={!item.isRun}>
                            选择</Button>
                      </div>
                    </div>
                  </div>
                </section>
              </div>
            )
          })
        }
      </div>
      <div className="bottom">
        <Button type='primary' onClick={save} style={{width:'200px',height:'50px',fontSize:'18px'}}>保存</Button>
      </div>
      <Modal
        title="选择积分商品"
        okText='确定'
        cancelText='取消'
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
        className='modal'
      >
        <p>ID:{modalText}</p>
        <div className="title">
          <span style={{marginRight:'10px',width:'30px'}}>类目</span>
          <Select defaultValue="请选择" style={{ width: 120 }} onChange={handleChange}>
            {
              goods.goodsType.map((i)=>{
                return  <Option key={i} value={i}>{i}</Option>
              })
            }
          </Select>
          <span style={{margin:'0 10px',width:'50px'}}>商品名称</span>
          <Input onKeyUp={keyUpHandler} ref={searchInput} placeholder='商品名称' style={{width:'200px',marginRight:'20px'}}></Input>
          <Button onClick={search} style={{backgroundColor:"#000",color:'white'}}>查询</Button>
        </div>
        <div className="container">
          <Table
            columns={columns}
            dataSource={goods.integralGoods}
            bordered
            rowSelection={{
              type:'checkbox',
              onChange(_,rows){
                // console.log(key,rows);
                setSleGoods(rows)
              }
            }}
          ></Table>
        </div>
      </Modal>
    </div>
  )
}

export default observer(Operate)